<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore, type Role } from '@/stores/user'

const router = useRouter()
const user = useUserStore()
const form = reactive<{ username: string; password: string; confirm: string; role: Role }>({
  username: '',
  password: '',
  confirm: '',
  role: 'viewer'
})
const loading = reactive({ submitting: false })
const formRef = ref()

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '至少 3 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '至少 6 位密码', trigger: 'blur' }
  ],
  confirm: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (_: any, value: string, callback: (err?: Error) => void) => {
        if (value !== form.password) callback(new Error('两次输入的密码不一致'))
        else callback()
      },
      trigger: 'blur'
    }
  ]
}

const submit = async () => {
  await formRef.value?.validate(async (valid: boolean) => {
    if (!valid) return
    loading.submitting = true
    try {
      await user.register(form.username, form.password, form.role)
      await user.login(form.username, form.password)
      router.replace('/')
    } catch (e: any) {
      alert(e?.message || '注册失败')
    } finally {
      loading.submitting = false
    }
  })
}
</script>

<template>
  <div class="register">
    <el-card class="card">
      <h2>注册</h2>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" @keyup.enter.native="submit">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="form.password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirm">
          <el-input type="password" v-model="form.confirm" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="form.role" style="width: 200px">
            <el-option label="管理员" value="admin" />
            <el-option label="编辑" value="editor" />
            <el-option label="访客" value="viewer" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading.submitting" :disabled="loading.submitting" @click="submit">注册并登录</el-button>
          <el-button link :disabled="loading.submitting" @click="router.push('/login')">返回登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
  
</template>

<style scoped>
.register { display:flex; align-items:center; justify-content:center; height:100vh; }
.card { width:380px; }
</style>


